import { IAdminState } from '@/models/adminModel';
import { IAdmin } from '@/types/admin';
import { PageContainer } from '@ant-design/pro-components';
import { message } from 'antd';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'umi';
import AdminForm from '../components/AdminForm';

const AddAdmin: React.FC = () => {
  const [newAdminInfo] = useState<IAdmin>({
    loginId: '',
    loginPwd: '',
    nickname: '',
    avatar: '',
    permission: 2, // 默认是普通管理员
  } as IAdmin);

  const { adminList }: IAdminState = useSelector((state: any) => state.admin);

  const dispatch = useDispatch();
  const navigate = useNavigate();

  function handleSubmit(value: any) {
    // 用户点击表单的确认时，要做的事儿
    // 接下来我们就需要进行新增操作
    const params = { ...value };
    if (value.avatar && value.avatar.file.status === 'done') {
      params.avatar = value.avatar.file.response.data;
    }
    dispatch({
      type: 'admin/_addAdmin',
      payload: params,
    });
    message.success('添加管理员成功');
    navigate('/admin/admin-list');
  }

  useEffect(() => {
    if (!adminList.length) {
      dispatch({
        type: 'admin/_initAdminList',
      });
    }
  }, [adminList]);

  return (
    <PageContainer>
      <div className="container" style={{ width: '500px' }}>
        <AdminForm
          type="add"
          adminInfo={newAdminInfo}
          handleSubmit={handleSubmit}
        />
      </div>
    </PageContainer>
  );
};

export default AddAdmin;
